import os
from io import BytesIO
from datetime import datetime, timedelta
import pandas as pd

path = os.path
from importlib import import_module, util
from datetime import datetime
import zipfile
import uuid
import requests
import time

sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]

session = requests.Session()
# 获取当前时间 T，并清空到当天的 00:00:00
T = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
# 定义两个关键时间节点
start_date = T - timedelta(days=7)  # T - 7 天 的 00:00:00
end_date = T - timedelta(days=38)  # T - 38 天 的 00:00:00
# 生成从 start_date 到 end_date 的时间序列，每7天一个节点（包含首尾）
current = start_date
date_list = []

while current >= end_date:
    date_list.append(current.strftime("%Y-%m-%dT%H:%M:%S.000+0800"))
    current -= timedelta(days=7)
# 构建区间 [[a,b], [b,c], [c,d], ...]
intervals = []
for i in range(len(date_list) - 1):
    intervals.append([date_list[i], date_list[i + 1]])
printer(intervals)

# archivedDateAfter :"归档时间开始"
# archivedDateBefore :"归档时间结束"
# "startTimeBefore": "派单时间开始"
# "startTimeAfter": "派单时间结束",

# productId:产品类型
# "388": "个人宽带"
# "389": "手机宽带"
# "prod.10086000031450": "智能安防",
# "prod.10086000032038": "全屋WIFI基础产品",
# "prod.10000007000048": "宽带父电视基础产品"
# "prod.10000007000049": "宽带子电视基础产品"
# "prod.10086000034031": "平安乡村基础产品"
# "prod.10086000048281": "全屋光网基础产品"
# "prod.10086000040928": "智能门锁基础产品"

# orderStatesIn: 订单状态
# 1:"服务开通中"
# 2:"工单报竣"

# businessTypeIn： 操作类型
# Install: "开通"
# DropSubs: "拆机"
# Remove: "移机"

payloads = [
    {
        "startTimeBefore": end_date.strftime("%Y-%m-%dT00:00:00.000+0800"),
        "archivedDateBefore": end_date.strftime("%Y-%m-%dT00:00:00.000+0800"),
        "productIdIn": ["388", "389"],
        "businessTypeIn": ["Install"],
        "orderStatesIn": [2],
        "sortBy": "state",
        "sortOrder": "asc",
        "queryOrderTag": "1",
    }
]
# 输出结果
for dt in intervals:
    payloads.append(
        {
            "startTimeAfter": dt[1],
            "startTimeBefore": dt[0],
            "productIdIn": [
                "388",
                "389",
            ],
            "businessTypeIn": ["Install"],
            "sortBy": "state",
            "sortOrder": "asc",
            "queryOrderTag": "1",
        }
    )

params = [
    {
        "file_name": "宽带开通数据A.xlsx",
        "download_path": path.join(data_path, r"开通类指标\源数据"),
        "payload": payloads,
    },
]


def download_file(uuid, file_name, download_path):
    url = f"http://sf.gmcc.net:27001/api/tasklist/order/export/download/{uuid}"

    while True:
        res = session.get(url)
        if res.status_code == 200:
            if isinstance(download_path, str):
                file_path = os.path.join(download_path, file_name)

                with open(file_path, "wb") as f:
                    f.write(res.content)
                printer(f"文件下载完成: {file_path}")
                return
            else:
                return res.content
        else:
            printer(f"下载中{res.status_code}")
        time.sleep(3)
    return


def create_export_task(uuid, payload):
    url = f"http://sf.gmcc.net:27001/api/tasklist/personal-order/export2/{uuid}?firstResult=0&maxResults=5000"
    res = session.post(url, json=payload)

    if res.status_code == 200:
        printer(res.json()["message"])
        return True
    else:
        printer("创建下载任务失败")


def check_export_status(uuid, browser):
    url = f"http://sf.gmcc.net:27001/api/tasklist/order/export/status/{uuid}"
    printer(f"正在导出数据({uuid})")
    while True:
        js_code = """async () => {{
          const res = await fetch("{url}")
          console.log("来自robot",res)
          if(res.status===200){{
            const json = await res.json();
            console.log(json)
            return json
          }}
          return res.status
        }}""".format(
            url=url
        )

        # 执行 JavaScript 并获取结果
        result = browser.evaluate_javascript("body", js_code)
        printer(result)
        if result != 204:
            if "type" in result and result["type"] == "success":
                printer("导出完成")
                return True
            # return True
        time.sleep(3)


def main():
    # sn.connect_to_internal()
    if sn.wait_for_system("sf.gmcc.net", "27001"):
        printer("服开系统已可用")
        printer("[下载数据] 开始")
        auth_info = import_module("login_fk").main()
        cookies = auth_info["cookies"]
        browser = auth_info["browser"]
        session.cookies.update(cookies)
        browser.go_to("http://sf.gmcc.net:27001/app/tasklist/default/#/order/personal")
        for param in params:
            file_name, download_path, payload = param.values()
            # return
            if isinstance(payload, list):
                printer(f"开始下载{file_name} {len(payload)}份文件")

                combined_df = pd.DataFrame()
                i = 1
                for pl in payload:
                    uuid = UUID()
                    create_res = create_export_task(uuid, pl)
                    if create_res:
                        printer(f"第{i}份文件创建导出任务成功: {uuid}")
                        time.sleep(1)
                        download_ready = check_export_status(uuid, browser)
                        if download_ready:
                            file_content = download_file(
                                uuid, f"{i}_{file_name}", False
                            )
                            printer(f"第{i}份文件下载完成")
                            excel_data = BytesIO(file_content)

                            # 使用 pandas 读取 Excel 文件
                            df = pd.read_excel(excel_data, engine="openpyxl")

                            # 合并数据 (假设所有文件有相同的表头)
                            combined_df = pd.concat(
                                [combined_df, df], ignore_index=True
                            )
                            i += 1
                printer("数据下载完成开始合并导出")
                combined_df.fillna("").astype(str).to_excel(
                    path.join(download_path, file_name), index=False, engine="openpyxl"
                )
            else:
                uuid = UUID()
                create_res = create_export_task(uuid, payload)
                if create_res:
                    printer(f"创建导出任务成功: {uuid}")
                    time.sleep(1)
                    download_ready = check_export_status(uuid, browser)
                    if download_ready:
                        download_file(uuid, file_name, download_path)

        printer("[下载数据] 👏 完成，总耗时<run_time>。", run_time="hh:mm:ss")


def UUID():
    return str(uuid.uuid4())
